package controller;

import dao.InoutDao;
import dao.RepertoryDao;
import dao.StockDao;
import entity.Stock;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.repertory;
import service.RepertorySDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/kucun")
public class Repertory {
    @Autowired
    public RepertoryDao repertoryDao;
    @Autowired
    public InoutDao inoutDao;
    @Autowired
    public RepertorySDao repertorySDao;
    @Autowired
    public StockDao stockDao;
    @RequestMapping("/showRepertory")//查询库存信息
    @ResponseBody
    public Map<String,Object> showRepertory(String repertoryName, String typeId, String firmId, int offset, int limit){
        try {
            if(repertoryName!=null){
                repertoryName = new String(repertoryName.getBytes("ISO-8859-1"),"utf-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(typeId==null){
            typeId="0";
        }
        if(firmId==null){
            firmId="0";
        }
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",repertoryDao.showRepertory(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId),offset,limit));
        map.put("total",repertoryDao.total(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId)));
         return map;
    }
    @RequestMapping("/showInout")//查询库存变动
    @ResponseBody
    public Map<String,Object> showInout( String repertoryName, String typeId, String lasttime, String times, int offset, int limit){
        if(typeId==null){
            typeId="0";
        }
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",inoutDao.showInout(repertoryName,Integer.parseInt(typeId),lasttime,times,offset,limit));
        map.put("total",inoutDao.totalInout(repertoryName,Integer.parseInt(typeId),lasttime,times));
        return map;
    }
    @RequestMapping("/uplowert")//查询库存变动
    @ResponseBody
    public  Map<String,Object> uplowest(entity.Repertory repertory){
        repertoryDao.uplowest(repertory);
       /* return showRepertory(null,"0","0",0,12);*/
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",repertoryDao.showRepertory(null,0,0,0,12));
        map.put("total",repertoryDao.total(null,0,0));
        return map;
    }
    @RequestMapping("/kucunbaojing")//库存报警
    @ResponseBody
    public Map<String,Object> showkucunbaojing(String repertoryName, String typeId, String firmId, int offset, int limit){
        Map<String,Object>map=new HashMap<>();
        List<entity.Repertory> list=repertoryDao.showRepertorys();//取出所有库存
        for (entity.Repertory repertory:list){//循环读出库存信息
            if(repertory.getRepertoryNum()<repertory.getLowest()){//判断库存量是否小于最低库存量
                int lack=repertory.getLowest()-repertory.getRepertoryNum();//计算缺货多少
                repertoryDao.upLack(repertory.getRepertoryId(),lack);//修改缺货数量
            }else{//解除报警
                repertoryDao.upjiechu(repertory.getRepertoryId());
            }
        }
        try {
            if(repertoryName!=null){
                repertoryName = new String(repertoryName.getBytes("ISO-8859-1"),"utf-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(typeId==null){
            typeId="0";
        }
        if(firmId==null){
            firmId="0";
        }
        map.put("rows",repertoryDao.showbaojing(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId),offset,limit));
        map.put("total",repertoryDao.totalbaojing(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId)));
        return map;
    }
    /**
     * 下载库存报警进货单excel表格
     * @param request
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fileDownloadData")
    public ResponseEntity<byte[]> fileDownloadData(HttpServletRequest request, HttpServletResponse resp)
            throws Exception {
        //加载表的所有数据
        List<entity.Repertory> list = repertoryDao.showbaojings();
        //在服务器上产生excel数据表格
         XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(new File("进货单.xlsx"))) ;
        //得到excel表格的每个worksheet
        XSSFSheet sheet = xwb.getSheetAt(0);
        //声明行
        XSSFRow row = null;
        //单元格样式
        XSSFCellStyle style = xwb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        XSSFFont font = xwb.createFont();// 创建字体对象
        font.setFontHeightInPoints((short) 15);// 设置字体大小
        style.setFont(font);
        for (int i=0;i<list.size();i++) {
            entity.Repertory repertory = list.get(i) ;
            row = sheet.createRow(i+1);
            //设置行高
            row.setHeight((short) 580);
            String repertoryName = repertory.getRepertoryName() ;
            String firmName = repertory.getFirm().getFirmName() ;
            String repertoryColor  = repertory.getRepertoryColor() ;
            String repertoryModel=repertory.getModel();
            String iphoneTypeName=repertory.getType().getIptypeName();
            int lack=repertory.getLack();
            XSSFCell cell0 = row.createCell(1) ;
            //设置单元格样式
            cell0.setCellStyle(style);
            XSSFCell cell1 = row.createCell(2) ;
            //设置单元格样式
            cell1.setCellStyle(style);
            //设置单元格样式
            XSSFCell cell2 = row.createCell(3) ;
            cell2.setCellStyle(style);
            XSSFCell cell3 = row.createCell(4) ;
            cell3.setCellStyle(style);
            XSSFCell cell4 = row.createCell(5) ;
            cell4.setCellStyle(style);
            XSSFCell cell5 = row.createCell(6) ;
            cell5.setCellStyle(style);
            cell0.setCellValue(repertoryName);
            cell1.setCellValue(repertoryModel);
            cell2.setCellValue(iphoneTypeName);
            cell3.setCellValue(repertoryColor);
            cell4.setCellValue(firmName);
            cell5.setCellValue(lack);

        }
        //格式化当前时间
        String strDate = new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(new Date());
        String fileName = "进货单"+strDate+".xlsx" ;
        //在服务器上生成数据
        FileOutputStream os = new FileOutputStream(fileName);
        xwb.write(os);
        os.close();// 关闭文件输出流

        byte[] body = null;
        File file = new File(fileName);
        InputStream in = new FileInputStream(file);
        body = new byte[in.available()];
        in.read(body);

        HttpHeaders headers = new HttpHeaders();
        String fname = new String(fileName.getBytes("gbk"), "iso8859-1");
        headers.add("Content-Disposition", "attachment;filename=" + fname);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        in.close();
        return response;
    }
    /**
     * 修改商品进价
     */
    @RequestMapping("/upprice")
    @ResponseBody
    public Map<String,Object> upprice(int repertoryId,double price,String repertoryName, String typeId, String firmId, int offset, int limit){
        repertorySDao.upkucun(repertoryId,price);
        try {
            if(repertoryName!=null){
                repertoryName = new String(repertoryName.getBytes("ISO-8859-1"),"utf-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(typeId==null){
            typeId="0";
        }
        if(firmId==null){
            firmId="0";
        }
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",repertoryDao.showRepertory(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId),offset,limit));
        map.put("total",repertoryDao.total(repertoryName,Integer.parseInt(typeId),Integer.parseInt(firmId)));
        return map;
    }
    /**
     * 统计库存报警有多少
     */
    @RequestMapping("/totalbaojing")
    @ResponseBody
    public int totalbaojing(){
        List<entity.Repertory> list=repertoryDao.showRepertorys();//取出所有库存
        for (entity.Repertory repertory:list){//循环读出库存信息
            if(repertory.getRepertoryNum()<repertory.getLowest()){//判断库存量是否小于最低库存量
                int lack=repertory.getLowest()-repertory.getRepertoryNum();//计算缺货多少
                repertoryDao.upLack(repertory.getRepertoryId(),lack);//修改缺货数量
            }else{//解除报警
                repertoryDao.upjiechu(repertory.getRepertoryId());
            }
        }
        return repertoryDao.totalbaojing(null,0,0);
    }
    /**
     * 加入到进货单中
     */
    @RequestMapping("/upzt")
    @ResponseBody
    public boolean upzt(String repertoryId){
        repertoryId = repertoryId.substring(0, repertoryId.length() - 1);//去掉最后一个字符
        System.out.println(repertoryId);
        String[] ids = repertoryId.split(",");//根据,拆分成数组
        for (int i = 0; i < ids.length; i++) {
           repertoryDao.upzt(Integer.parseInt(ids[i]));
        }
        return true;
    }
    /**
     * 下载进货单excel表格
     * @param request
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fileDownloadDatas")
    public ResponseEntity<byte[]> fileDownloadDatas(HttpServletRequest request, HttpServletResponse resp)
            throws Exception {
        //加载表的所有数据
        List<Stock> list=stockDao.showsstock();
        //在服务器上产生excel数据表格
        XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(new File("进货单1.xlsx"))) ;
        //得到excel表格的每个worksheet
        XSSFSheet sheet = xwb.getSheetAt(0);
        //声明行
        XSSFRow row = null;
        //单元格样式
        XSSFCellStyle style = xwb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        XSSFFont font = xwb.createFont();// 创建字体对象
        font.setFontHeightInPoints((short) 15);// 设置字体大小
        style.setFont(font);
        for (int i=0;i<list.size();i++) {
            Stock stock = list.get(i) ;
            row = sheet.createRow(i+1);
            //设置行高
            row.setHeight((short) 580);
            String repertoryName = stock.getShop().getShopName() ;//商品名称
            String firmName = stock.getFirm().getFirmName() ;//厂商名称
            String repertoryColor  = stock.getShop().getShopcolor() ;//商品颜色
            String repertoryModel=stock.getShop().getShopType();//商品型号
            String iphoneTypeName=stock.getIphonetype().getIptypeName();//商品类别
            int lack=stock.getStockNum();//进货数量
            double total=stock.getStockTotal();//总价钱
            double price=stock.getShop().getShopprice();//单价
            XSSFCell cell0 = row.createCell(1) ;
            //设置单元格样式
            cell0.setCellStyle(style);
            XSSFCell cell1 = row.createCell(2) ;
            //设置单元格样式
            cell1.setCellStyle(style);
            //设置单元格样式
            XSSFCell cell2 = row.createCell(3) ;
            cell2.setCellStyle(style);
            XSSFCell cell3 = row.createCell(4) ;
            cell3.setCellStyle(style);
            XSSFCell cell4 = row.createCell(5) ;
            cell4.setCellStyle(style);
            XSSFCell cell5 = row.createCell(6) ;
            cell5.setCellStyle(style);
            XSSFCell cell6 = row.createCell(7) ;
            cell6.setCellStyle(style);
            XSSFCell cell7 = row.createCell(8) ;
            cell7.setCellStyle(style);

            cell0.setCellValue(repertoryName);
            cell1.setCellValue(repertoryModel);
            cell2.setCellValue(iphoneTypeName);
            cell3.setCellValue(repertoryColor);
            cell4.setCellValue(firmName);
            cell5.setCellValue(lack);
            cell6.setCellValue(price);
            cell7.setCellValue(total);

        }
        //格式化当前时间
        String strDate = new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(new Date());
        String fileName = "进货单1"+strDate+".xlsx" ;
        //在服务器上生成数据
        FileOutputStream os = new FileOutputStream(fileName);
        xwb.write(os);
        os.close();// 关闭文件输出流

        byte[] body = null;
        File file = new File(fileName);
        InputStream in = new FileInputStream(file);
        body = new byte[in.available()];
        in.read(body);

        HttpHeaders headers = new HttpHeaders();
        String fname = new String(fileName.getBytes("gbk"), "iso8859-1");
        headers.add("Content-Disposition", "attachment;filename=" + fname);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        in.close();
        return response;
    }
}
